package com.cisetech.util.email;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cisetech.util.Global;


public class EmailUtils {
	private final static Logger log = LoggerFactory.getLogger(EmailUtils.class);

	private static final String FROM = Global.getConfig("FROM_EMAIL");//"liyang_668@126.com";//"要发送邮件的邮箱，这个例子是163邮箱";
	private static final String POSSWORD = Global.getConfig("FROM_EMAIL_POSSWORD");//"liyang57";////设置账号和密码（密码为从网易获取的固定密码，并非登录密码，只是给第三方登录用的密码）
	
	public static void sendAccountActivateEmail(String toEmail,String url) throws MessagingException {
		log.info("发送邮箱至："+toEmail);
		log.info("返回rul："+url);
		Session session = getSession();
		MimeMessage message = new MimeMessage(session);
		message.setSubject("这是一封激活账号的邮件，复制链接到地址栏来激活他");
		message.setSentDate(new Date());
		message.setFrom(new InternetAddress(EmailUtils.FROM));//服务器邮箱
		message.setRecipient(RecipientType.TO, new InternetAddress(toEmail));//客户邮箱
		message.setContent("<a target='_BLANK' href='"+url+"'>点击激活账号</a>",
				"text/html;charset=utf-8");
//			message.setContent("1111111","text/html;charset=utf-8");
		log.info("设置好参数开始发送邮件");
		Transport.send(message);
		log.info("邮件发送成功");
	}

	public static Session getSession() {
		String port = "456";
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        final Properties p = System.getProperties() ;
        p.setProperty("mail.smtp.host", "SMTP.126.com");
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.user", EmailUtils.FROM);
        p.setProperty("mail.smtp.pass", EmailUtils.POSSWORD);
        
        p.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        p.setProperty("mail.smtp.socketFactory.fallback", "false");
        //邮箱发送服务器端口,这里设置为465端口
        p.setProperty("mail.smtp.port", port);
        p.setProperty("mail.smtp.socketFactory.port", port);

       // 根据邮件会话属性和密码验证器构造一个发送邮件的session
       Session session = Session.getInstance(p, new Authenticator(){
           protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
           }
       });
       session.setDebug(true);
		return session;
	}
	public static void main(String[] args) {
		try {
			sendAccountActivateEmail("1182929528@qq.com","http://www.baidu.com");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
